package com.jsh.erp.service.rebate;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.*;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static com.jsh.erp.utils.Tools.getCenternTime;

@Service
public class RebateService {
    private Logger logger = LoggerFactory.getLogger(RebateService.class);

    @Resource
    private RebateMapper rebateMapper;

    @Resource
    private RebateMapperEx rebateMapperEx;

    @Resource
    private RebateMaterialMapper rebateMaterialMapper;

    @Resource
    private RebateMaterialMapperEx rebateMaterialMapperEx;

    @Resource
    private RebateRuleMapper rebateRuleMapper;

    @Resource
    private RebateRuleMapperEx rebateRuleMapperEx;

    @Resource
    private RebateItemMapper rebateItemMapper;

    @Resource
    private RebateItemMapperEx rebateItemMapperEx;

    @Resource
    private UserService userService;

    @Resource
    private SystemConfigService systemConfigService;

    public Rebate getRebate(String id)throws Exception {
        Rebate result=null;
        try{
            result=rebateMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<Rebate> getRebate()throws Exception {
        RebateExample example = new RebateExample();
        example.createCriteria();
        List<Rebate> list=null;
        try{
            list=rebateMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<Rebate> select(String rebateCode, int offset, int rows)throws Exception {
        List<Rebate> resList = new ArrayList<Rebate>();
        List<Rebate> list=null;
        try{
            list=rebateMapperEx.selectByConditionRebate(rebateCode, offset, rows);
            if (null != list) {
                for (Rebate dh : list) {
                    if (dh.getStartTime()!=null){
                        dh.setStartTimeStr(getCenternTime(dh.getStartTime()));
                    }
                    if (dh.getEndTime()!=null){
                        dh.setEndTimeStr(getCenternTime(dh.getEndTime()));
                    }
                    if (dh.getCreateTime()!=null){
                        dh.setCreateTimeStr(getCenternTime(dh.getCreateTime()));
                    }
                    if (dh.getUpdateTime()!=null){
                        dh.setUpdateTimeStr(getCenternTime(dh.getUpdateTime()));
                    }
                    if (dh.getTabulationTime()!=null){
                        dh.setTabulationTimeStr(getCenternTime(dh.getTabulationTime()));
                    }
                    resList.add(dh);
                }
            }
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return resList;
    }


    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertRebate(JSONObject obj, HttpServletRequest request) throws Exception{
        Rebate rebate = JSONObject.parseObject(obj.toJSONString(), Rebate.class);
        rebate.setUploadFlag("0");
        int result=0;
        try{
//            User userInfo=userService.getCurrentUser();
//            rebate.setCreator(userInfo==null?null:userInfo.getId());
            result=rebateMapper.insertSelective(rebate);
//            doSaveRebateMaterial(obj,rebate.getId(),rebate.getSupplierId(),"insert");
//            doSaveRebateRule(obj,rebate.getId(),"insert");
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        doSaveRebateItem(obj,rebate.getId(),"insert");
        return result;
    }



    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateRebate(JSONObject obj, HttpServletRequest request) throws Exception{
        Rebate rebate = JSONObject.parseObject(obj.toJSONString(), Rebate.class);
        rebate.setUploadFlag("0");
        int result=0;
        try{
            result = rebateMapper.updateByPrimaryKeySelective(rebate);
//            doSaveRebateMaterial(obj,rebate.getId(),rebate.getSupplierId(),"update");
//            doSaveRebateRule(obj,rebate.getId(),"update");
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        doSaveRebateItem(obj,rebate.getId(),"update");
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteRebate(String id, HttpServletRequest request)throws Exception {
        int result=0;
        try{
            result=updateDeleteFlag(id);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    /**
     * 修改单个返利删除标志
     * @param id
     * @return
     * @throws Exception
     */
    public int updateDeleteFlag(String id)throws Exception {
        int result=0;
        try{
            Rebate rebate=rebateMapper.selectByPrimaryKey(id);
            rebate.setDeleteFlag("1");
            rebate.setUploadFlag("0");
            result = rebateMapper.updateByPrimaryKey(rebate);
//            RebateRule rebateRule = new RebateRule();
//            rebateRule.setDeleteFlag("1");
//            RebateRuleExample ruleExample = new RebateRuleExample();
//            ruleExample.createCriteria().andRebateIdEqualTo(id);
//            rebateRuleMapper.updateByExampleSelective(rebateRule,ruleExample);
//            RebateMaterial rebateMaterial = new RebateMaterial();
//            rebateMaterial.setDeleteFlag("1");
//            RebateMaterialExample rebateMaterialExample = new RebateMaterialExample();
//            rebateMaterialExample.createCriteria().andRebateIdEqualTo(id);
//            rebateMaterialMapper.updateByExampleSelective(rebateMaterial,rebateMaterialExample);
            RebateItem rebateItem = new RebateItem();
            rebateItem.setDeleteFlag("1");
            rebateItem.setUploadFlag("0");
            RebateItemExample rebateItemExample = new RebateItemExample();
            rebateItemExample.createCriteria().andRebateIdEqualTo(id);
            rebateItemMapper.updateByExampleSelective(rebateItem,rebateItemExample);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    /**
     * 修改多个返利删除标志
     * @param ids
     * @return
     * @throws Exception
     */
    public int updateDeleteFlagS(List<String> ids)throws Exception {
        int result=0;
        try{
            Rebate rebate= new Rebate();
            rebate.setDeleteFlag("1");
            rebate.setUploadFlag("0");
            RebateExample rebateExample = new RebateExample();
            rebateExample.createCriteria().andIdIn(ids);
            result = rebateMapper.updateByExample(rebate,rebateExample);
//            RebateRule rebateRule = new RebateRule();
//            rebateRule.setDeleteFlag("1");
//            RebateRuleExample ruleExample = new RebateRuleExample();
//            ruleExample.createCriteria().andRebateIdIn(ids);
//            rebateRuleMapper.updateByExampleSelective(rebateRule,ruleExample);
//            RebateMaterial rebateMaterial = new RebateMaterial();
//            rebateMaterial.setDeleteFlag("1");
//            RebateMaterialExample rebateMaterialExample = new RebateMaterialExample();
//            rebateMaterialExample.createCriteria().andRebateIdIn(ids);
//            rebateMaterialMapper.updateByExampleSelective(rebateMaterial,rebateMaterialExample);
            RebateItem rebateItem = new RebateItem();
            rebateItem.setDeleteFlag("1");
            rebateItem.setUploadFlag("0");
            RebateItemExample rebateItemExample = new RebateItemExample();
            rebateItemExample.createCriteria().andRebateIdIn(ids);
            rebateItemMapper.updateByExampleSelective(rebateItem,rebateItemExample);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteRebate(String ids, HttpServletRequest request)throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        int result=0;
        try{
            result=updateDeleteFlagS(idList);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

//    public int updateRebateByKey(String platformKey, String platformValue)throws Exception {
//        int result=0;
//        try{
//            Rebate rebate = new Rebate();
//            rebate.setPlatformValue(platformValue);
//            RebateExample example = new RebateExample();
//            example.createCriteria().andPlatformKeyEqualTo(platformKey);
//            result = rebateMapper.updateByExampleSelective(rebate, example);
//        }catch(Exception e){
//            JshException.writeFail(logger, e, systemConfigService.getLanCode());
//        }
//        return result;
//    }

    public Rebate getRebateByKey(String rebateCode)throws Exception {
        Rebate rebate = new Rebate();
        try{
            RebateExample example = new RebateExample();
            example.createCriteria().andRebateCodeEqualTo(rebateCode).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            List<Rebate> list=rebateMapper.selectByExample(example);
            if(list!=null && list.size()>0){
                rebate = list.get(0);
            }
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return rebate;
    }

    public Long countRebate(String rebateCode) {
        Long result = null;
        try {
            result = rebateMapperEx.countRebate(rebateCode);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<RebateMaterial> getRebateMaterialByRebateId(String id)throws Exception {
        List<RebateMaterial> list=null;
        try{
            RebateMaterialExample example = new RebateMaterialExample();
            example.createCriteria().andRebateIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list=rebateMaterialMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<RebateRule> getRebateRuleByRebateId(String id)throws Exception {
        List<RebateRule> list=null;
        try{
            RebateRuleExample example = new RebateRuleExample();
            example.createCriteria().andRebateIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list=rebateRuleMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<RebateItem> getRebateItemByRebateId(String id)throws Exception {
        List<RebateItem> list=null;
        try{
            RebateItemExample example = new RebateItemExample();
            example.createCriteria().andRebateIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list=rebateItemMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }


//    private void doSaveRebateMaterial(JSONObject obj, String id,String supplierId, String type) {
//        try {
//            Set<String> existsSets = Sets.newHashSet();
//            if ("update".equals(type)) {
//                List<RebateMaterial> existsVOS = getRebateMaterialByRebateId(id);
//                existsVOS.stream().forEach(existsVO -> {
//                    existsSets.add(existsVO.getId());
//                });
//            }
//            //先处理增加，修改
//            List<RebateMaterial> rebateMaterialList = JSONObject.parseArray(obj.getJSONArray("rebateMaterialList").toJSONString(), RebateMaterial.class);
//            if(rebateMaterialList != null) {
//
//                List<String> ids = new ArrayList<>();
//                rebateMaterialList.stream().forEach(rebateMaterial -> {
//                    ids.add(rebateMaterial.getMaterialId());
//                });
//                HashSet<String> set = new HashSet<>(ids);
//                Boolean result = set.size() == ids.size() ? true : false;
//                if(!result){
//                    throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "返利商品不能重复");
//                }
//                for (RebateMaterial rebateMaterial : rebateMaterialList) {
//                    rebateMaterial.setRebateId(id);
//                    if (existsSets.contains(rebateMaterial.getId())) {
//                        existsSets.remove(rebateMaterial.getId());
//                        rebateMaterialMapper.updateByPrimaryKeySelective(rebateMaterial);
//                        continue;
//                    }
//                    rebateMaterial.setId(IdUtils.getUUID());
//                    String name = rebateMapperEx.selSupplierMaterial(supplierId,rebateMaterial.getMaterialId(),id);
//                    if (StringUtils.isNotEmpty(name)) {
//                        throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "商品"+name+"已存在其他返利活动");
//                    }
//                    rebateMaterialMapper.insertSelective(rebateMaterial);
//                }
//            }else {
//                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "返利商品不能为空");
//            }
//            //然后 删除
//            for (String rebateMaterialId : existsSets) {
//                rebateMaterialMapper.deleteByPrimaryKey(rebateMaterialId);
//            }
//        } catch (Exception e) {
//            JshException.writeFail(logger, e, systemConfigService.getLanCode());
//        }
//    }

//    private void doSaveRebateRule(JSONObject obj, String id, String type) {
//        try {
//            Set<String> existsSets = Sets.newHashSet();
//            if ("update".equals(type)) {
//                List<RebateRule> existsVOS = getRebateRuleByRebateId(id);
//                existsVOS.stream().forEach(existsVO -> {
//                    existsSets.add(existsVO.getId());
//                });
//            }
//            //先处理增加，修改
//            List<RebateRule> rebateRuleList = JSONObject.parseArray(obj.getJSONArray("rebateRuleList").toJSONString(), RebateRule.class);
//            if(rebateRuleList != null) {
//
//
//                for (RebateRule rebateRule : rebateRuleList) {
//                    rebateRule.setRebateId(id);
//                    if (existsSets.contains(rebateRule.getId())) {
//                        existsSets.remove(rebateRule.getId());
//                        rebateRuleMapper.updateByPrimaryKeySelective(rebateRule);
//                        continue;
//                    }
//                    rebateRule.setId(IdUtils.getUUID());
//                    rebateRuleMapper.insertSelective(rebateRule);
//                }
//            }else {
//                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE, "返利设置不能为空");
//            }
//            //然后 删除
//            for (String rebateRuleId : existsSets) {
//                rebateRuleMapper.deleteByPrimaryKey(rebateRuleId);
//            }
//        } catch (Exception e) {
//            JshException.writeFail(logger, e, systemConfigService.getLanCode());
//        }
//    }

    private void doSaveRebateItem(JSONObject obj, String id, String type) throws Exception {
        String lanCode = systemConfigService.getLanCode();
            Set<String> existsSets = Sets.newHashSet();
            if ("update".equals(type)) {
                List<RebateItem> existsVOS = getRebateItemByRebateId(id);
                existsVOS.stream().forEach(existsVO -> {
                    existsSets.add(existsVO.getId());
                });
            }
            //先处理增加，修改
            List<RebateItem> rebateItemList = JSONObject.parseArray(obj.getJSONArray("meList").toJSONString(), RebateItem.class);
            if(rebateItemList != null) {
                for (RebateItem rebateItem : rebateItemList) {
                    rebateItem.setRebateId(id);
                    rebateItem.setUploadFlag("0");
                    if (existsSets.contains(rebateItem.getId())) {
                        existsSets.remove(rebateItem.getId());
                        rebateItemMapper.updateByPrimaryKeySelective(rebateItem);
                    }else {
                        rebateItem.setId(IdUtils.getUUID());
                        rebateItemMapper.insertSelective(rebateItem);
                    }
                }
            }else {
                throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,  "zh".equals(lanCode) ? "返利设置不能为空" : "The rebate setting cannot be empty");
            }
            //然后 删除
            for (String rebateRuleId : existsSets) {
//                rebateRuleMapper.deleteByPrimaryKey(rebateRuleId);
                rebateRuleMapperEx.batchDeleteRebateRuleById(rebateRuleId);
            }
    }

    public List<RebateVo> rebateDetails(String supplierId,Integer pageNum,Integer pageSize){
        return rebateMapperEx.rebateDetails(supplierId,pageNum,pageSize);
    }

    public Long rebateDetailsCount(String supplierId){
        return rebateMapperEx.rebateDetailsCount(supplierId);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetRebateTenant(String ids,String syncTenantId) throws Exception {
        int result =0;
        List<String> idList = StringUtil.strToStringList(ids);
        RebateExample example=new RebateExample();
        example.createCriteria().andIdIn(idList);
        Rebate entity=new Rebate();
        entity.setSyncTenantId(syncTenantId);
        try{
            result=  rebateMapper.updateByExampleSelective(entity, example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    public BigDecimal getRebateAmount(String supplierId, String materialId , BigDecimal operNumber, Date createTime){
        BigDecimal rebateAmount = BigDecimal.ZERO;
        try {
            rebateAmount=rebateMapperEx.getRebateAmount(supplierId, materialId, operNumber, createTime);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return rebateAmount;
    }
}
